package com.wswy.wyjk.ui.practice

import android.support.v4.content.ContextCompat
import android.support.v7.widget.RecyclerView
import android.text.SpannableString
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import android.view.ViewStub
import android.widget.ImageView
import android.widget.TextView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.my.httpapi.api.baseUtils.LogUtils
import com.raft.framework.ui.adapter.SampleRecyclerViewAdapter
import com.wswy.wyjk.AppContext
import com.wswy.wyjk.R
import com.wswy.wyjk.model.PracticeData
import com.wswy.wyjk.model.vo.PracticeModel
import com.wswy.wyjk.ui.drawable.CenterImageSpan
import com.wswy.wyjk.ui.drawable.QuestionTypeDrawable
import com.wswy.wyjk.ui.practice.interface1.PracticeToOnline
import com.wswy.wyjk.ui.widget.OptionImageView
import com.wswy.wyjk.utils.ToastUtils
import com.wswy.wyjk.utils.gone
import com.wswy.wyjk.utils.loadLayout
import com.wswy.wyjk.utils.visible
import timber.log.Timber

class PracticeAdapter(
    private val practiceViewModel: PracticeViewModel,
    val practiceToOnline: PracticeToOnline
) :
    SampleRecyclerViewAdapter<PracticeModel, PracticeAdapter.PracticeViewHolder>() {

    private companion object {
        private const val TAG = "PracticeAdapter"

    }

    //几种颜色
    private val colorNormal =
        ContextCompat.getColor(AppContext.getContext(), R.color.textColorPrimary)
    private val colorRight = ContextCompat.getColor(AppContext.getContext(), R.color.colorPrimary)
    private val colorWrong = ContextCompat.getColor(AppContext.getContext(), R.color.textColorWrong)

    private val judgeDrawable by lazy {
        QuestionTypeDrawable(AppContext.getContext().getString(R.string.judge_question))
    }
    private val radioDrawable by lazy {
        QuestionTypeDrawable(AppContext.getContext().getString(R.string.radio_question))
    }
    private val multipleDrawable by lazy {
        QuestionTypeDrawable(AppContext.getContext().getString(R.string.multiple_question))
    }

    private var errCount = 0

    override fun onCreateViewHolder(parent: ViewGroup, position: Int): PracticeViewHolder {
        return PracticeViewHolder(loadLayout(parent, R.layout.layout_practice_item))
    }

    override fun onBindViewHolder(holder: PracticeViewHolder, position: Int, data: PracticeModel?) {
        data?.run {

            holder.tvQuestion.text =
                SpannableString(" ${position + 1}. ${practiceData.question}").apply {

                    when (practiceData.optionType) {
                        PracticeData.TYPE_JUDGE -> judgeDrawable
                        PracticeData.TYPE_RADIO -> radioDrawable
                        PracticeData.TYPE_MULTIPLE -> multipleDrawable
                        else -> null
                    }?.let {

                        setSpan(CenterImageSpan(it), 0, 1, SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)

                    }

                }

            holder.tvOptionA.text = practiceData.optionA
            holder.tvOptionB.text = practiceData.optionB



            holder.rlOptionA.setTag(R.id.item_view_holder, holder)
            holder.rlOptionB.setTag(R.id.item_view_holder, holder)
            holder.rlOptionC.setTag(R.id.item_view_holder, holder)
            holder.rlOptionD.setTag(R.id.item_view_holder, holder)

            holder.rlOptionA.setTag(R.id.item_data, this)
            holder.rlOptionB.setTag(R.id.item_data, this)
            holder.rlOptionC.setTag(R.id.item_data, this)
            holder.rlOptionD.setTag(R.id.item_data, this)

            holder.rlOptionA.setOnClickListener(optionClickListener)
            holder.rlOptionB.setOnClickListener(optionClickListener)
            holder.rlOptionC.setOnClickListener(optionClickListener)
            holder.rlOptionD.setOnClickListener(optionClickListener)

            if (practiceViewModel.alreadyReply(practiceData.id) || practiceViewModel.uiData.isExplainModel()) {
                //当前模式，有答题记录或者是背题模式

                //当前做过题了，可以比较区分答案
                val compareAnswer = practiceViewModel.alreadyReply(practiceData.id)

                renderComplete(this, holder, compareAnswer)
            } else {
                renderPractice(this, holder)
            }

            //题目图片
            if (TextUtils.isEmpty(practiceData.mediaUrl)) {
                holder.imgQuestion.gone()
            } else {
                holder.imgQuestion.visible()
                val option = RequestOptions.placeholderOf(R.drawable.image_timu_default)
                    .error(R.drawable.image_timu_default)
                Glide.with(holder.imgQuestion).load(practiceData.mediaUrl).apply(option)
                    .into(holder.imgQuestion)
            }

            //判断题  或 选择题 部分隐藏
            if (TextUtils.isEmpty(practiceData.optionC)) {
                holder.rlOptionC.gone()
            } else {
                holder.rlOptionC.visible()
                holder.tvOptionC.text = practiceData.optionC
            }

            if (TextUtils.isEmpty(practiceData.optionD)) {
                holder.rlOptionD.gone()
            } else {
                holder.rlOptionD.visible()
                holder.tvOptionD.text = practiceData.optionD
            }

        }

    }


    //答题模式
    private fun renderPractice(practiceModel: PracticeModel, holder: PracticeViewHolder) {

        holder.resetOption()

        holder.hideExplain()

        //多选显示确认按钮
        if (practiceModel.practiceData.isMultipleSelection() || practiceViewModel.isExamMode()) {
            holder.tvConfirm.visible()
            holder.tvConfirm.setOnClickListener(multipleClickListener)

            holder.tvConfirm.setTag(R.id.item_view_holder, holder)
            holder.tvConfirm.setTag(R.id.item_data, practiceModel)

        } else {
            holder.tvConfirm.gone()
            holder.tvConfirm.setOnClickListener(null)
        }

    }

    //结果模式
    private fun renderComplete(
        practiceModel: PracticeModel,
        holder: PracticeViewHolder,
        compareAnswer: Boolean = false
    ) {

        holder.rlOptionA.setOnClickListener(null)
        holder.rlOptionB.setOnClickListener(null)
        holder.rlOptionC.setOnClickListener(null)
        holder.rlOptionD.setOnClickListener(null)

        val imgOpts = arrayOf(holder.imgOptA, holder.imgOptB, holder.imgOptC, holder.imgOptD)
        val tvOpts = arrayOf(holder.tvOptionA, holder.tvOptionB, holder.tvOptionC, holder.tvOptionD)

        val stA = practiceModel.practiceData.answer

        val myA = practiceModel.recordData?.getTypeAnswer() ?: 0

        Timber.e("stA  ${stA}   myA ${myA} ")

        //处理答案
        for (i in 0..3) {

            val stBit = (1 shl (i + 4) and stA)
            val myBit = (1 shl (i + 4) and myA)

            //Timber.e("    st  i ${i} ${stBit} ${myBit} ")

            if (compareAnswer) {

                //比较答案
                if (stBit == myBit) {
                    //现在是正确答案
                    if (stBit != 0) {
                        imgOpts[i].setRightState()
                        tvOpts[i].setTextColor(colorRight)
                    } else {
                        //不是正确答案，但是也都没选
                        imgOpts[i].setNormalState()
                        tvOpts[i].setTextColor(colorNormal)
                    }
                } else {
                    if (stBit != 0) {
                        //这是正确答案
                        imgOpts[i].setRightState()
                        tvOpts[i].setTextColor(colorRight)
                    } else {
                        //这是用户选的答案
                        imgOpts[i].setWrongState()
                        tvOpts[i].setTextColor(colorWrong)
                    }
                }

            } else {

                //不比较答案，只显示正确的  背题模式并且没做

                if (stBit != 0) {
                    //这是正确答案
                    imgOpts[i].setRightState()
                    tvOpts[i].setTextColor(colorRight)
                } else {
                    imgOpts[i].setNormalState()
                    tvOpts[i].setTextColor(colorNormal)
                }
            }
        }

        //显示 题目解析

        holder.showExplain(practiceModel.practiceData)

    }

    //做题 提交
    private fun doSubmit(holder: PracticeViewHolder, data: PracticeModel, options: IntArray) {

        var op = 0

        //多选合并选项
        options.forEach {
            op = (1 shl (4 + it)) or op
        }
        errCount = practiceViewModel.uiData.wrongCount
        practiceViewModel.addRecord(data, op)
        if (practiceViewModel.uiData.wrongCount > errCount) {
            practiceToOnline.err(data.practiceData.id)
        }

    }


    //点击答案选项 -- 单选
    private val optionClickListener = View.OnClickListener { v ->

        val data = (v.getTag(R.id.item_data) as? PracticeModel) ?: return@OnClickListener

        (v.getTag(R.id.item_view_holder) as? PracticeViewHolder)?.let {

            var option = -1  //选项顺序

            //考试模式
            if (practiceViewModel.isExamMode()) {
                if (!data.practiceData.isMultipleSelection()) {
                    it.resetState()
                }
                it.tvConfirm.visible()
            }

            if (v === it.rlOptionA) {

                it.imgOptA.setSelectToggle()

                option = 0

            } else if (v === it.rlOptionB) {

                it.imgOptB.setSelectToggle()

                option = 1

            } else if (v === it.rlOptionC) {

                it.imgOptC.setSelectToggle()

                option = 2

            } else if (v === it.rlOptionD) {

                it.imgOptD.setSelectToggle()

                option = 3

            }

            //开始答题 保存记录 单选
            //非多选直接提交
            if (!data.practiceData.isMultipleSelection() && !practiceViewModel.isExamMode()) {
                doSubmit(it, data, intArrayOf(option))
            }


        }

    }

    //多选提交
    private val multipleClickListener = View.OnClickListener { v ->
        val data = (v.getTag(R.id.item_data) as? PracticeModel) ?: return@OnClickListener

        (v.getTag(R.id.item_view_holder) as? PracticeViewHolder)?.let {
            val opts = arrayListOf<Int>()
            if (it.imgOptA.isOptionChecked()) {
                opts.add(0)
            }
            if (it.imgOptB.isOptionChecked()) {
                opts.add(1)
            }
            if (it.imgOptC.isOptionChecked()) {
                opts.add(2)
            }
            if (it.imgOptD.isOptionChecked()) {
                opts.add(3)
            }

            if (opts.size < 2 && data.practiceData.isMultipleSelection()) {
                //至少选2项
                ToastUtils.showText("请至少选择两项")
            } else {
                //多选 可用提交
                doSubmit(it, data, opts.toIntArray())
            }

        }
    }

    override fun onViewRecycled(holder: PracticeViewHolder) {
        super.onViewRecycled(holder)

        holder.resetOption()
    }

    class PracticeViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        private val colorNormal =
            ContextCompat.getColor(AppContext.getContext(), R.color.textColorPrimary)

        val imgQuestion: ImageView = itemView.findViewById(R.id.img_question)
        val tvQuestion: TextView = itemView.findViewById(R.id.tv_question)

        val tvOptionA: TextView = itemView.findViewById(R.id.tv_option_a)
        val tvOptionB: TextView = itemView.findViewById(R.id.tv_option_b)
        val tvOptionC: TextView = itemView.findViewById(R.id.tv_option_c)
        val tvOptionD: TextView = itemView.findViewById(R.id.tv_option_d)

        val imgOptA: OptionImageView = itemView.findViewById(R.id.img_option_a)
        val imgOptB: OptionImageView = itemView.findViewById(R.id.img_option_b)
        val imgOptC: OptionImageView = itemView.findViewById(R.id.img_option_c)
        val imgOptD: OptionImageView = itemView.findViewById(R.id.img_option_d)

        val rlOptionA: View = itemView.findViewById(R.id.rl_option_a)
        val rlOptionB: View = itemView.findViewById(R.id.rl_option_b)
        val rlOptionC: View = itemView.findViewById(R.id.rl_option_c)
        val rlOptionD: View = itemView.findViewById(R.id.rl_option_d)

        val tvConfirm: TextView = itemView.findViewById(R.id.tv_submit)


        lateinit var layoutExplain: View
        lateinit var tvExplainQuestion: TextView
        lateinit var tvExplainInfo: TextView

        private var isLoaded = false

        fun loadExplain() {
            if (!isLoaded) {
                itemView.findViewById<ViewStub>(R.id.vs_explain)?.let {

                    val explainLayout = it.inflate()

                    layoutExplain = explainLayout.findViewById(R.id.ll_practice_explain)
                    tvExplainQuestion = explainLayout.findViewById(R.id.tv_explain_question)
                    tvExplainInfo = explainLayout.findViewById(R.id.tv_explain_info)
                    isLoaded = true

                }
            }
        }

        fun showExplain(practiceData: PracticeData) {
            loadExplain()

            if (isLoaded && this::layoutExplain.isInitialized) {

                layoutExplain.visible()
                tvExplainQuestion.text =
                    itemView.context.getString(R.string.explain_question, practiceData.answerStr)

                tvExplainInfo.text =
                    itemView.context.getString(R.string.explain_question_info, practiceData.explain)
            }
        }

        fun hideExplain() {
            if (isLoaded && this::layoutExplain.isInitialized) {
                layoutExplain.gone()
            }
        }

        fun resetState() {
            imgOptA.resetState()
            imgOptB.resetState()
            imgOptC.resetState()
            imgOptD.resetState()

            tvOptionA.setTextColor(colorNormal)
            tvOptionB.setTextColor(colorNormal)
            tvOptionC.setTextColor(colorNormal)
            tvOptionD.setTextColor(colorNormal)
        }

        fun resetOption() {
            resetState()



            tvConfirm.gone()
            imgQuestion.gone()
        }
    }
}